<template>
  <div>
    <div>
    <el-card class="filter-container" shadow="never">
      <div>
        <h2 class="h1 hero-title">
          <strong><i class="el-icon-shopping-cart-2"></i>购物车</strong>
        </h2>
      </div>
      <div style="margin: 10px">
        <el-input style="width:200px" suffix-icon="el-icon-search" placeholder="商品名称" v-model="productName"></el-input>
        <el-button style="margin-left: 5px" type="primary" @click="load">搜索</el-button>
      </div>

      <template>
        <el-table :data="tableData" @selection-change="handleSelectionChange" border>
          <el-table-column type="selection" width="45"></el-table-column>
          <el-table-column prop="productPic" label="商品图片" width="125" align="center">
            <template v-slot="scope">
              <el-image :src="scope.row.productPic" ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" align="center" width="250">
          </el-table-column>
          <el-table-column prop="price" label="单价" align="center">
          </el-table-column>
          <el-table-column prop="quantity" label="数量" align="center" width="160">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" @change="handleChange(scope.row)" :min="1" :max="10" ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="金额" align="center" >
            <template slot-scope="scope">
              <div style="color: orangered">{{scope.row.price * scope.row.quantity}}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-popconfirm
                  class="ml-5"
                  confirm-button-text='确定'
                  cancel-button-text='我再想想'
                  icon="el-icon-info"
                  icon-color="red"
                  title="确认删除宝贝吗？"
                  @confirm="handleDel(scope.row.id)"
              >
                <el-button slot="reference">删除</el-button>
              </el-popconfirm>
            </template>>
          </el-table-column>
        </el-table>
      </template>

      <div style="padding: 10px 0">
        <el-pagination
            :page-sizes="[5,10,15,20]"
            :page-size="pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            layout="total,  prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </el-card>
    </div>
    <div class="fixed">
      <div style="padding: 10px 0"><small>已选商品</small><span style="color: orangered"><strong>{{totalNum}}</strong></span><small>件</small></div>
      <div style="padding: 10px 0"><small>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp合计(不含运费)</small>:<span style="color: orangered">￥<strong>{{totalPrice}}</strong></span></div>
      &nbsp&nbsp&nbsp&nbsp
      <el-button style="color: white; background: orangered" size="medium" round @click="handleSettled1">结算</el-button>
    </div>

    <el-dialog title="填写订单" :visible.sync="dialogFormVisible" width="80%">
      <el-form label-width="150px" size="small">
        <el-form-item label="收件人">
          <el-input
              :rows="1"
              placeholder="请输入收件人姓名"
              v-model="receiverName">
          </el-input>
        </el-form-item>

        <el-form-item label="联系方式">
          <el-input
              :rows="1"
              placeholder="请输入收件人电话"
              v-model="receiverPhone">
          </el-input>
        </el-form-item>

        <el-form-item label="收货地址" :inline="true">
          <v-distpicker :province="province"
                        :city="city"
                        :area="region"
                        @selected="onSelectRegion"></v-distpicker>
          <el-input v-model="receiverAddress" autocomplete="off" placeholder="请输入详细地址" style="width: 300px;margin-top: 10px">
          </el-input>
          <el-button @click="fill" type="primary" plain style="margin-left: 20px">表单填充</el-button>
        </el-form-item>

        <el-form-item label="商品信息">
          <el-table :data="productList">
            <el-table-column prop="productPic" label="商品图片" width="125" align="center">
              <template v-slot="scope">
                <el-image :src="scope.row.productPic" ></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" align="center" width="250">
            </el-table-column>
            <el-table-column prop="quantity" label="数量" align="center" width="160">
            </el-table-column>
            <el-table-column label="总金额" align="center" >
              <template slot-scope="scope">
                <div style="color: orangered">{{scope.row.price * scope.row.quantity}}</div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="订单总金额">
          <div>{{this.totalPrice}}</div>
        </el-form-item>

        <el-form-item label="优惠券">
          <el-table :data="couponList"  highlight-current-row ref="singleTable" @selection-change="handleSelectionChange1">
            <el-table-column type="selection" width="55" :selectable="checkSelectable"></el-table-column>
            <el-table-column prop="name" label="优惠券名称" width="125" align="center">
            </el-table-column>
            <el-table-column prop="minPoint" label="使用门槛" align="center" width="250">
            </el-table-column>
            <el-table-column prop="amount" label="金额" align="center" width="160">
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="优惠金额">
          <div>{{this.couponAmount}}</div>
        </el-form-item>

        <el-form-item label="应付金额">
          <div>{{this.totalPrice- this.couponAmount}}</div>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="textarea">
          </el-input>
        </el-form-item>
      </el-form>
      <div style="margin-top: 20px;text-align: center">
        <el-button type="primary" @click="handleSubmit">提交订单</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import VDistpicker from 'v-distpicker';
export default {
  name: "ShoppingCart",
  components: {
    VDistpicker
  },
  data(){
    return {
      memberId:localStorage.getItem("id"),
      user:localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) :{},
      multipleSelection: [],
      productName:[],
      total:0,
      pageNum:1,
      pageSize:5,
      tableData:[],
      totalPrice:0,
      totalNum:0,
      receiverName:'',
      receiverPhone:'',
      orderId:0,
      order:{},
      dialogFormVisible:false,
      orderItemsList:{},
      couponList:{},
      productList:{},
      radio:'',
      textarea:'',
      couponAmount:0,
      receiverAddress:'',
      orderItem:{},
      region:'',
      city:'',
      province:''
    }
  },
  created() {
    this.load()
  },
  methods:{
    load(){
      //请求查询数据
      this.request.get("/cart/page",{
        params:{
          pageNum:this.pageNum,
          pageSize:this.pageSize,
          productName:this.productName,
          memberId:this.memberId
        }
      }).then(res =>{
        console.log(res)
        this.tableData = res.records
        this.total = res.total
      })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.singleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.singleTable.clearSelection();
      }
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
    handleDel(id){
      this.request.delete("/cart/"+id).then(res=>{
        if(res){
          this.$message.success("删除成功")
          this.load()
        }else{
          this.$message.error("删除失败")
        }
      })
    },
    handleSelectionChange(val) {
      this.totalPrice = 0
      this.totalNum = 0
      this.multipleSelection = val;
      //进行计算
      if(val && val.length){
        val.forEach(item=>{
          this.totalPrice += item.price*item.quantity
          this.totalNum += 1
        })
      }
      this.totalPrice = this.totalPrice.toFixed(2)
      this.discountAmount = this.totalPrice
    },
    handleSelectionChange1(val) {
      this.couponAmount = 0
      this.multipleSelection = val;
      //进行计算
      if(val && val.length){
        val.forEach(item=>{
          this.couponAmount = item.amount
        })
      }
      if (val.length > 1) {
        this.$refs.singleTable.clearSelection()
        this.$refs.singleTable.toggleRowSelection(val.pop())
      }
    },
    delBatch(){
      let ids = this.multipleSelection.map(v => v.id)
      this.request.post("/cart/del/batch",ids).then(res=>{
        if(res){
          this.$message.success("批量删除成功")
          this.load()
        }else{
          this.$message.error("批量删除失败")
          this.load()
        }
      })
    },
    handleChange(row){
      this.request.post("/cart/setNum",row).then(res=>{
        if(res){
          // this.load()
        }else{
          this.$message.error("修改失败")
        }
      })
      this.totalPrice = 0

      this.multipleSelection.forEach(item=>{
        this.totalPrice+=item.price*row.quantity
      })

      this.totalPrice = this.totalPrice.toFixed(2)
    },
    handleSettled(){
      let ids = this.multipleSelection.map(v => v.id)
      this.textarea = ''
      this.request.post("/cart/settled",ids).then(res=>{
        if(res){
          this.$message.success("请填写订单")
          this.orderId = res.data
          this.load()
          this.findProducts()
          this.editOrder()
          this.findAbleCoupon()
        }else{
          this.$message.error("结算失败")
          this.load()
        }
      })
    },
    handleSettled1(){
      let ids = this.multipleSelection.map(v => v.id)
      this.findAbleCoupon()
      this.textarea = ''
      this.receiverAddress=''
      this.receiverPhone=''
      this.receiverName=''
      this.city = ''
      this.region = ''
      this.province = ''
      this.request.post("/cart/getProductList",ids).then(res=>{
        if(res){
          this.productList = res.data
          console.log(this.productList)
          this.dialogFormVisible = true
          // this.load()
          // this.editOrder()
          // this.findAbleCoupon()
        }else{
          this.$message.error("结算失败")
          this.load()
        }
      })
    },
    editOrder(){
      this.request.get("/order/getById/"+this.orderId).then(res=>{
        this.order = res.data
        this.dialogFormVisible = true
      })
    },
    findProducts(){
      this.request.get("/order/getOrderItems/"+this.orderId).then(res=>{
        this.orderItemsList = res.data
      })
    },
    findAbleCoupon(){
      this.request.get("/couponhistories/getAbleCoupon/"+this.memberId).then(res=>{
        this.couponList = res.data
      })
    },
    checkSelectable(row) {
      return row.minPoint <= this.totalPrice
    },
    handleSubmit(){
      if(this.$refs.singleTable.selection[0]==null)
      {this.order.couponId = null}
      else{this.order.couponId = this.$refs.singleTable.selection[0].couponId}
      this.order.couponAmount = this.couponAmount
      this.order.payAmount = this.totalPrice - this.couponAmount
      this.order.payType = 0
      this.order.totalAmount = this.totalPrice
      this.order.sourceType = 0
      this.order.status = 0
      this.order.memberId = this.memberId
      this.order.orderType = 0
      this.order.receiverProvince  = this.province
      this.order.receiverCity = this.city
      this.order.receiverRegion = this.region
      this.order.note = this.textarea
      this.order.memberUsername = this.user.nickname
      this.order.receiverName = this.receiverName
      this.order.receiverPhone = this.receiverPhone
      this.order.receiverDetailAddress = this.receiverAddress
      console.log(this.order)
      this.request.post("/order/buy",JSON.stringify(this.order)).then(res=>{
        if(res){
          this.$message.success("下单成功，请及时支付")
          this.orderId = res.data
          this.dialogFormVisible = false
          console.log(this.orderId)
          this.addOrderItem()
          this.load()
          location.reload()
        }else{
          this.$message.error("服务器开小差啦")
          this.dialogFormVisible = false
        }
      })
    },
    addOrderItem(){
      for(let i=0;i<this.productList.length;i++){
        this.orderItem.orderId= this.orderId
        this.orderItem.productId = this.productList[i].productId
        this.orderItem.productPic = this.productList[i].productPic
        this.orderItem.productName = this.productList[i].productName
        this.orderItem.productSn = this.productList[i].productSn
        this.orderItem.productPrice = this.productList[i].price
        this.orderItem.productQuantity = this.productList[i].quantity
        this.orderItem.realAmount = this.orderItem.productPrice*this.orderItem.productQuantity
        this.orderItem.spData = this.productList[i].spData
        this.orderItem.productSubTitle = this.productList[i].productSubTitle
        this.request.post("/order/addOrderItem",JSON.stringify(this.orderItem)).then(res=>{
          console.log("第一次")
        })
      }
    },
    onSelectRegion(data) {
      this.province = data.province.value;
      this.city = data.city.value;
      this.region = data.area.value;
    },
    fill(){
      this.request.get("/user/" + localStorage.getItem("id")).then(res => {
        console.log(res.province)
        this.province = res.province
        this.city = res.city
        this.region = res.region
        this.receiverAddress = res.detailAddress
        this.receiverName = res.nickname
        this.receiverPhone = res.phone
      })
    }
  }
}
</script>

<style scoped>
.fixed{
  position: fixed;
  bottom: 0;
  height: 50px;
  width: 75%;
  display: flex;
  justify-content: flex-end;
}

.r{
  position:absolute;
  right:5px;
  bottom:5px;
}
</style>